﻿//show specific product declare and must know information and hide it
function PolicyDeclareContentHideAndShow() {
    //wanguo
    $("#mustwanguo").click(function () {
        $("#divmustwanguo").toggle();
    })

    $("#declarewanguo").click(function () {
        $("#divdeclarewanguo").toggle();
    })

    //leyouyou
    $("#mustleyouyou").click(function () {
        $("#divmustleyouyou").toggle();
    })

    $("#declareleyouyou").click(function () {
        $("#divdeclareleyouyou").toggle();
    })

    //wanmei
    $("#mustwanmei").click(function () {
        $("#divmustwanmei").toggle();
    })

    $("#declarewanmei").click(function () {
        $("#divdeclarewanmei").toggle();
    })

    //baodao
    $("#mustbaodao").click(function () {
        $("#divmustbaodao").toggle();
    })

    $("#declarebaodao").click(function () {
        $("#divdeclarebaodao").toggle();
    })

    //changyoushenzhou
    $("#mustchangyoushenzhou").click(function () {
        $("#divmustchangyoushenzhou").toggle();
    })

    $("#declarechangyoushenzhou").click(function () {
        $("#divdeclarechangyoushenzhou").toggle();
    })

    //wanlitong
    $("#mustwanlitong").click(function () {
        $("#divmustwanlitong").toggle();
    })

    $("#declarewanlitong").click(function () {
        $("#divdeclarewanlitong").toggle();
    })

    //xiaotanxian
    $("#mustxiaotanxian").click(function () {
        $("#divmustxiaotanxian").toggle();
    })

    $("#declarexiaotanxian").click(function () {
        $("#divdeclarexiaotanxian").toggle();
    })
}
//only show current product
function PolicyDeclareTitletHideAndShow(productCode) {
    //wanguo
    $("#wanguo").hide();
    $("#leyouyou").hide();
    $("#wanmei").hide();
    $("#baodao").hide();
    $("#changyoushenzhou").hide();
    $("#wanlitong").hide();
    $("#xiaotanxian").hide();

    //leyouyou
    if (productCode == "020932") {
        $("#leyouyou").show();
    }
    //wanguo
    else if (productCode == "020933") {
        $("#wanguo").show();
    }
    //changyoushenzhou
    else if (productCode == "020934") {
        $("#changyoushenzhou").show();
    }
    //xiaotanxian
    else if (productCode == "020936") {
        $("#xiaotanxian").show();
    }
    //wanlitong
    else if (productCode == "021037") {
        $("#wanlitong").show();
    }
    //baodao
    else if (productCode == "021085") {
        $("#baodao").show();
    }
    //wanmei
    else if (productCode == "021043") {
        $("#wanmei").show();
    }
}

// Add by Lynn 2014/07/24 Start
function TravelDestinationsHideAndShow(productCode) {

    // changyoushenzhou
    $("#travelDes_changyoushenzhou").hide();
    $("#travelDes_other").hide();

    //leyouyou
    if (productCode == "020934") {
        $("#travelDes_changyoushenzhou").show();
    }
    else {
        $("#travelDes_other").show();
    }
}
// Add by Lynn 2014/07/24 End

function CheckProductMaxDuration() {

    var end = $("#PolicyEndDate").val();
    var start = $("#PolicyStartDate").val();
    var days = DiffLong(start, end) + 1;

    var maxDay = $("#HidproductDuration").val();

    if (days > maxDay) {
        //alert("选择的天数超过产品最大天数");
        $("#PolicyEndDate").parent().find(".error").html("选择的天数超过产品最大天数");
        return false
    }

    return true;
}

function checkInsuredBirthDay(obj) {

    if (obj.id.indexOf("Insured") >= 0) {
        var birthday = $(obj).val();

        //policy duration is from policy start date, not today[Bright 20140710]
        var policyStartDate = $("#PolicyStartDate").val();

        var min = parseInt($("#HidminOld").val());
        var max = parseInt($("#HidmaxOld").val());
        if (!DateIsInRange(birthday, policyStartDate, min, max + 1)) {
            $(obj).parent().find(".error").html("被保险人的年龄必须在(" + min + "," + max + ")之间");
        }
        else {
            $(obj).parent().find(".error").html("");
        }
    }
}

function checkInsuredBirthDay_obj(obj) {
    if (obj.id.indexOf("Insured") >= 0) {
        var birthday = obj.val();
        //policy duration is from policy start date, not today[Bright 20140710]
        var policyStartDate = $("#PolicyStartDate").val();

        var min = parseInt($("#HidminOld").val());
        var max = parseInt($("#HidmaxOld").val());
        if (!DateIsInRange(birthday, policyStartDate, min, max + 1)) {
            obj.parent().find(".error").html("被保险人的年龄必须在(" + min + "," + max + ")之间");
        }
        else {
            obj.parent().find(".error").html("");
        }
    }
}

function OpenScopeFee() {
    var url_prefix = "../Home/ScopeFee/";
    var url = "";
    var productCode = $("#ProductCode").val();

    if (productCode == "020932") {
        url = "https://www.aig.com.cn/individuals/travel-insurance/asia-travel-insurance.html";
    } else if (productCode == "020933") {
        url = "https://www.aig.com.cn/individuals/travel-insurance/international-travel-insurance.html";
    } else if (productCode == "020934") {
        url = "https://www.aig.com.cn/individuals/travel-insurance/domestic-travel-insurance.html";
    } else if (productCode == "021085") {
        url = "https://www.aig.com.cn/individuals/travel-insurance/taiwan-travel-insurance.html";
    } else if (productCode == "021043") {
        url = "https://www.aig.com.cn/individuals/travel-insurance/usa-travel-insurance.html";
    } else {
        url = url_prefix + productCode;
    }

    window.open(url);
}

function BackProductInfo() {
    var url = "../Home/Index/";
    //var productCode = $("#ProductCode").val();
    //url += productCode;
    document.location = url;
}

function ResetInsuredSequnce(index, removeButton) {
    //refresh insured index after remove one insured
    var current, next;
    next = $("#Insured" + index + "RELATION_CODE").parents(".new_him"); //
    if (next == null || next.html() == null) {
        next = $("#InsuredPersons_" + index + "__RELATION_CODE").parents(".new_him");
        //}
    }
    if (next == null || next.html() == null) {
        next = $(removeButton).parents(".new_him").next();
    }

    $(removeButton).parents(".new_him").remove();

    while (next.html() != null) {

        //replace the index value
        var oldtitleString = "被保人" + (index + 1);
        var newtitleString = "被保人" + index;
        var oldidString = "Insured" + index;
        var newidString = "Insured" + (index - 1);
        var oldnameString = "InsuredPersons." + index;
        var newnameString = "InsuredPersons[" + (index - 1);

        var newhtmlContent = next.html();
        //alert11(newhtmlContent.indexOf(oldnameString)); find("input[name$= BIRTH_DATE]");
        //Name or Name 
        //NAME,RELATION_CODE,ID_TYPE_ID,ID_NO,BIRTH_DATE,GENDER,MOBILE
        //Name,ID_TYPE_ID,ID_NO,RELATION_CODE,Gender,Mobile,BIRTH_DATE
        var birth, name, relation, id_type, id_no, gener, mobile;
        //Birthday
        //birth = next.find("input[id$= BIRTH_DATE]").val();
        if (next.find("input[id$= BIRTH_DATE]").html() == null) {
            birth = next.find("input[id$= Birthday]").val();
        }
        else {
            birth = next.find("input[id$= BIRTH_DATE]").val();
        }
        //name
        if (next.find("input[id$= Name]") == null) {
            name = next.find("input[id$= NAME]").val();
        }
        else {
            name = next.find("input[id$= Name]").val();
        }
        //relation
        relation = next.find("select[id$= RELATION_CODE]").val();
        //id_type = next.find("select[id$= ID_TYPE_ID]").val();
        if (next.find("select[id$= ID_TYPE_ID]").html() == null) {
            id_type = next.find("select[id$= ID_Type_ID]").val();
        }
        else {
            id_type = next.find("select[id$= ID_TYPE_ID]").val();
        }
        id_no = next.find("input[id$= ID_NO]").val();
        //gender
        if (next.find("input[id$= Gender]").html() == null) {
            gener = next.find("input[id$= GENDER]").attr("checked")
        }
        else {
            gener = next.find("input[id$= Gender]").attr("checked");
        }
        //mobile
        if (next.find("input[id$= MOBILE]").html() == null) {
            mobile = next.find("input[id$= Mobile]").val();
        }
        else {
            mobile = next.find("input[id$= MOBILE]").val();
        }

        newhtmlContent = newhtmlContent.replace(new RegExp(oldidString, 'g'), newidString);
        newhtmlContent = newhtmlContent.replace(new RegExp(oldnameString, 'g'), newnameString);
        newhtmlContent = newhtmlContent.replace(new RegExp(oldtitleString, 'g'), newtitleString);

        next.html(newhtmlContent);

        //set control value
        if (next.find("input[id$= BIRTH_DATE]").html() == null) {
            next.find("input[id$= Birthday]").val(birth);
        }
        else {
            next.find("input[id$= BIRTH_DATE]").val(birth);
        }
        //name
        if (next.find("input[id$= Name]") == null) {
            next.find("input[id$= NAME]").val(name);
        }
        else {
            next.find("input[id$= Name]").val(name);
        }
        //relation
        next.find("select[id$= RELATION_CODE]").val(relation);

        //id type id
        if (next.find("select[id$= ID_TYPE_ID]").html() == null) {
            next.find("select[id$= ID_Type_ID]").val(id_type);
        }
        else {
            next.find("select[id$= ID_TYPE_ID]").val(id_type);
        }
        next.find("input[id$= ID_NO]").val(id_no);
        //gender
        if (gener == "checked") {
            next.find(".male").attr('checked', true);
        }
        else {
            next.find(".female").attr('checked', true);
        }

        //mobile
        if (next.find("input[id$= MOBILE]").html() == null) {
            next.find("input[id$= Mobile]").val(mobile);
        }
        else {
            next.find("input[id$= MOBILE]").val(mobile);
        }
        //alert(newhtmlContent);
        //alert(next.html());

        index = (index + 1);
        next = next.next();
    }
}

function isDate(obj) {
    var a = /((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)$))/

    if (!a.test(obj)) {
        //alert(1);
        return false;
    }
    //alert(2);
    return true;
}

function checkDate(obj) {
    var DATE_FORMAT = /^[0-9]{4}-[0-1]?[0-9]{1}-[0-3]?[0-9]{1}$/;
    var birthday = obj.val();
    //alert(birthday);
    obj.parent().find(".error").html("");
    if (!DATE_FORMAT.test(birthday)) {

        obj.parent().find(".error").html("日期格式必须为YYYY-MM-DD");
        //alert("");
    }
    if (birthday.length > 10) {
        obj.parent().find(".error").html("日期格式必须为YYYY-MM-DD");
    }

    if (birthday.substring(6, 7) == '-' && birthday.length == 9 && birthday.substring(4, 5) == '-') {
        birthday = birthday.substring(0, 5) + '0' + birthday.substring(5, 10);
        obj.val(birthday);
    }

    else if (birthday.substring(7, 8) == '-' && birthday.length == 9 && birthday.substring(4, 5) == '-') {
        birthday = birthday.substring(0, 8) + '0' + birthday.substring(8, 10);
        obj.val(birthday);
    }

    else if (birthday.substring(6, 7) == '-' && birthday.length == 8 && birthday.substring(4, 5) == '-') {
        birthday = birthday.substring(0, 5) + '0' + birthday.substring(7, 8) + '-0' + birthday.substring(7, 10);
        obj.val(birthday);
    }
    else if (birthday.substring(4, 5) != '-' || birthday.substring(7, 8) != '-') {
        obj.parent().find(".error").html("日期格式必须为YYYY-MM-DD");
        return;
    }
    if (birthday.substring(5, 7) == '00' || birthday.substring(8, 10) == '00') {
        obj.parent().find(".error").html("请输入有效日期格式");
    }
}

function checkDateFormat(obj) {
    var birthday = obj.val();
    if (birthday.substring(6, 7) == '-' && birthday.length == 9) {
        birthday = birthday.substring(0, 5) + '0' + birthday.substring(5, 10);
        //alert(birthday.substring(5, 6));
        obj.val(birthday);
    }

    else if (birthday.substring(7, 8) == '-' && birthday.length == 9) {
        birthday = birthday.substring(0, 8) + '0' + birthday.substring(8, 10);
        //alert(birthday.substring(5, 6));
        obj.val(birthday);
    }

    else if (birthday.substring(6, 7) == '-' && birthday.length == 8) {
        birthday = birthday.substring(0, 5) + '0' + birthday.substring(5, 6) + '-0' + birthday.substring(7, 10);
        //alert(birthday.substring(5, 6));
        obj.val(birthday);
    }
    if (birthday.substring(5, 7) == '00' || birthday.substring(8, 10) == '00') {
        obj.parent().find(".error").html("请输入有效日期格式");
    }
}

function isCardNo(card, obj) {
    // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (reg.test(card) === false) {
        //alert("请输入正确的身份证号码");
        //$(obj).addClass("aa");
        $(obj).parent().find(".error").html("请输入正确的身份证号码");
        //alert($(obj).parent().find(".error").attr("class"));
        //$(".error").show().html("请输入正确的身份证号码");
        return false;
    } else {
        $(obj).parent().find(".error").html("");
        //alert("合法");
    }
}

function is18(obj) {
    var UUserCard = obj.val();
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate() - 1;

    if (UUserCard.length == 18) {
        var age = myDate.getFullYear() - UUserCard.substring(6, 10);
        if (age < 18 || (age == 18 && UUserCard.substring(10, 12) > month) || (age == 18 && UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) > day)) {
            obj.parent(".example").find(".error").html("投保人年龄必须大于或等于18岁");
            return false;
        }
    }
    else if (UUserCard.length == 15) {
        var age = myDate.getFullYear() - UUserCard.substring(6, 8) - 1900;
        if (age < 18 || (age == 18 && UUserCard.substring(8, 10) > month) || (age == 18 && UUserCard.substring(8, 10) == month && UUserCard.substring(10, 12) > day)) {
            obj.parent(".example").find(".error").html("投保人年龄必须大于或等于18岁");
            return false;
        }
    }
}

function is18Picker(obj) {
    var UUserDate = obj.val();
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate() - 1;
    var age = myDate.getFullYear() - UUserDate.substring(0, 4);

    if (UUserDate.length == 10) {

        if (age < 18 || (age == 18 && UUserDate.substring(5, 7) > month) || (age == 18 && UUserDate.substring(5, 7) == month && UUserDate.substring(8, 10) > day)) {
            obj.parent(".example").find(".error").html("投保人年龄必须大于或等于18岁");
            return false;
        }
    }
}

function isLength(len, obj, str) {
    if (obj.val().length > len) {
        obj.parent().find('.error').html(str);
    }
    else {
        obj.parent().find('.error').html('');
    }
}

function checkName(obj, errorDesc) {
    if (obj.val().match(/\d+/g)) {
        obj.parent().find('.error').html(errorDesc);
    }
}

function isCardNoYes(card, obj) {
    // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    var date_birth = new Date();
    var UUserCard = obj.val();
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;

    if (reg.test(card) === true) {
        obj.parent(".example").find("select option[value='身份证']").attr("selected", true);
        if (UUserCard.length == 18) {
            var birthdate = UUserCard.substring(6, 10);
            if (birthdate > date_birth.getFullYear() || birthdate < 1900) {

                obj.parent(".example").find(".error").html("请输入身份证有效年份");
                return false;
            }

            if (UUserCard.substring(10, 12) > 13 || UUserCard.substring(12, 14) > 31) {
                obj.parent(".example").find(".error").html("请输入身份证有效出生日期");
                return false;
            }
            birthdate = birthdate + "-" + UUserCard.substring(10, 12) + "-" + UUserCard.substring(12, 14);
            obj.parent().parent().parent().find(".datepicker").val(birthdate);
            obj.parent().parent().parent().find(".datepicker").prev(".tips_2").hide();
            obj.parent().parent().parent().find(".datepicker").next().next().html('');
            //Gender
            if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
                //male                    
                obj.parent().parent().parent().find(".sexual").get(0).checked = true;
            } else {
                //female                   
                obj.parent().parent().parent().find(".sexual").get(1).checked = true;
            }
        }
        else if (UUserCard.length == 15) {
            //check whether it is 19XX or 20XX 
            var birthdate = UUserCard.substring(6, 8);
            //alert(birthdate);
            if (birthdate > 20) {
                birthdate = "19" + birthdate;
            }
            else {
                birthdate = "20" + birthdate;
            }
            if (birthdate > date_birth.getFullYear() || birthdate < 1900) {

                obj.parent(".example").find(".error").html("请输入身份证有效年份");
                return false;
            }

            //alert(age);
            if (UUserCard.substring(8, 10) > 13 || UUserCard.substring(10, 12) > 31) {
                obj.parent(".example").find(".error").html("请输入身份证有效出生日期");
                return false;
            }
            //add month and date string
            birthdate = birthdate + "-" + UUserCard.substring(8, 10) + "-" + UUserCard.substring(10, 12);
            $(obj).parent().parent().parent().find(".datepicker").val(birthdate);
            $(obj).parent().parent().parent().find(".datepicker").prev(".tips_2").hide();
            //Gender
            if (parseInt(UUserCard.substr(13, 1)) % 2 == 1) {
                //male
                $("input[name=ApplicantGender]").get(0).checked = true;
            } else {
                //female
                $("input[name=ApplicantGender]").get(1).checked = true;
            }
        }
    }


}
function checkDisclaimer() {
    $("#btnSubmit").attr("disabled", "true");

    // Add by Lynn 2014/07/17 Start
    // Check Insured person duplicate
    //checkInsuredDuplicate();
    // Add by Lynn 2014/07/17 End

    var errorFlag = true;

    // Input required
    $(".must_input,.datepicker,.isName,#ApplicantIdNumber,.idNo").each(function () {
        if ($.trim($(this).attr("value")) == '') {
            $(this).parent('.example').find('.error').html("此项为必填项");
        }
    });

    // Select required
    $('#new_him_html').find('select').each(function () {
        if ($(this).find("option:selected").text() == "请选择") {
            $(this).parent().find('.error').html('此项为必填项');
        }
    });

    // If there is a error in insured list, open the first error div.
    $('#new_him_html').find('.error').each(function () {
        if ($(this).html() != '') {
            $('.him_cont').hide();
            $('.him_title ').addClass('title_current');
            $(this).parents('.him_cont').show();
            $(this).parents('.him_cont').prev().removeClass('title_current');
            return false;
        }
    });

    // Express required
    if ($('#ExpressRequired').attr("checked")) {
        if ($("#ExpressReceiverProvince").find("option:selected").text() == "请选择") {
            $("#ExpressReceiverProvince").parent().find(".express_1").html('请选择相应省份');
        }

        $("#expressCheck").find(".must_input").each(function () {
            if ($(this).attr("value") == '') {
                $(this).parent().find('.express_1').html("此项为必填项");
            }
        });
    }
    else {
        $("#expressCheck").find(".express_1").html('');
    }

    // Delete anchor before
    if ($("#Anchor").length > 0) {
        $("#Anchor").remove();
    }

    $(".error").each(function () {
        if ($.trim($(this).html()) != '') {

            // Add Anchor
            var anchor = "<a id='Anchor' name='errAnchor'></a>";
            $(this).parents(".row1").append(anchor);
            window.location.hash = "errAnchor";
            errorFlag = false;

            return false;
        }
    });

    // add check code[UAT defect 19]
    if ($("#checkCode").attr("value") == '') {
        var errorMessage = "请输入验证码";
        $("#checkCodeError").html(errorMessage);
        errorFlag = false;
    }

    if ($("#CanSave").attr("checked") && errorFlag == true) {
        $("#diclamerErrorMessage").html("");

        document.forms[0].submit();
    }
    else {
        if (!$("#CanSave").attr("checked")) {
            var errorMessage = "请选中申明条款";
            $("#diclamerErrorMessage").html(errorMessage);
        }
        $("#btnSubmit").removeAttr("disabled");
        return false;
    }
    //DWA TRACKING CODE
    var productCode = $('#ProductCode option:selected').val();

    switch (productCode) {
        case "020933":
            YoTrack(' https://log2.air.yoyi.com.cn/air/t?s=2208'); //SPOT3
            break;
        case "020932":
            YoTrack(' https://log2.air.yoyi.com.cn/air/t?s=2210'); //SPOT5
            break;
        case "020934":
            YoTrack(' https://log2.air.yoyi.com.cn/air/t?s=2212'); //SPOT7
            break;
        case "021085":
            YoTrack(' https://log2.air.yoyi.com.cn/air/t?s=2214'); //SPOT9
            break;
        case "021043":
            YoTrack(' https://log2.air.yoyi.com.cn/air/t?s=2216'); //SPOT11
            break;
    }

    return true;
}
//DWA TRACKING SOURCE CODE
function YoTrack(url) {
    var d = new Image(1, 1);
    d.src = url + "&r=" + Math.random();
    d.onload = function () { d.onload = null; }
};


function getPlans(productCode, isFirst, transactionId) {
    //hide other product declare
    PolicyDeclareTitletHideAndShow(productCode);

    // Add by Lynn 2014/07/24 Start
    TravelDestinationsHideAndShow(productCode);
    // Add by Lynn 2014/07/24 End

    $.ajaxAntiForgery({
        url: "GetPlansByProductCode",
        data: { productCode: productCode, isFirst: isFirst, transactionId: transactionId },
        dataType: "json",
        type: "POST",
        error: function () {
            alert("获取产品计划失败");
        },
        success: function (data) {
            var items = "";
            var appendItem;
            var i = 0;
            $("#planTable").empty();
            items += "<tr>";

            //insured and year old limitation 
            var maxOld = data["insuredOldEnd"];
            var minOld = data["insuredOldFrom"];
            var isOverSee = data["isOverSee"];
            var productDuration = data["productDuration"];

            $("#HidmaxOld").val(maxOld);
            $("#HidminOld").val(minOld);
            $("#HidisOverSee").val(isOverSee);
            $("#HidproductDuration").val(productDuration);

            //check insured birthday valid
            $('.datepicker').each(function () {
                checkInsuredBirthDay(this);
            })
            // var item = data.items[3].item;
            $.each(data["plans"], function (i, item) {
                i++;
                if (i >= 3 && i % 3 == 1) {
                    items += "</tr>";

                    appendItem = $(items);
                    $("#planTable").append($(appendItem))
                    items = "";
                    items = "<tr>";
                }
                if (item.Selected) {
                    //alert('1');
                    items += "<td><input type='radio'  id='PlanCode' name='PlanCode' value=\"" + item.Value + "\" checked='checked'><span>" + item.Text + "</span></input></td>";
                }
                else {
                    items += "<td><input type='radio'  id='PlanCode' name='PlanCode' value=\"" + item.Value + "\"><span>" + item.Text + "</span></input></td>";
                }
            });

            items += "</tr>";
            appendItem = $(items);
            $("#planTable").append($(appendItem));

            //if it is internal travel, disable checkbox of traval place 
            if (isOverSee == "0") {
                $("#citySelect").val("国内(不含港澳台)");
                $("#citySelect").attr("readonly", "");
            }
            else {
                if (!isFirst) {
                    $("#citySelect").val("");
                }
                //$("#citySelect").removeAttr("readonly");
                $("#citySelect").attr("readonly", "");
            }
            //if it is “宝岛游”
            if (productCode == '021085') {
                $("#citySelect").val("台湾");
                $("#citySelect").attr("readonly", "");
            }
            ////if it is ““完美”境外”
            //if (productCode == '021043') {
            //    $("#citySelect").val("美国");
            //    $("#citySelect").attr("readonly", "");
            //}
            // Check the radio button AGAIN to workaround the bug of Safari 5.
            // Safari5 sometime won't show a radio as a Checked even it has attribute checked='checked'.
            $("#planTable input[name='PlanCode'][checked='checked']").each(function () {
                $(this).attr("checked", "checked");
            });

            BindPlanRadioButtonEvent();

            getPricesFirst(isFirst);
        }
    })
}

function getPriceControlReset(isFirst, fullyearflag) {
    if (fullyearflag == "True") {
        $("#FullYearFlag").removeAttr("disabled");
    }
    else {
        $("#FullYearFlag").attr("disabled", "");
    }

    if (!isFirst) {
        if ($("#FullYearFlag").attr("checked")) {

            $("#FullYearFlag").attr("checked", false);
            $("#fullyearhide").show();
            $("#fullyearhidetext").show();

            var end = $("#PolicyEndDate").val();
            var start = $("#PolicyStartDate").val();
            var days = DiffLong(start, end) + 1;
        }
    }
    else {
        if ($("#FullYearFlag").attr("checked")) {
            $("#fullyearhide").hide();
            $("#fullyearhidetext").hide();
            var days = 365;
            $("#FullYearFlag").removeAttr("disabled");
        }
    }
}

//get first price by click product
function getPricesFirst(isFirst) {
    var plancode = $('input:radio[id="PlanCode"]:checked').val();//$("#PlanCode").val();
    var productCode = $("#ProductCode").val();
    var policyStartDate = $("#PolicyStartDate").val();
    var policyEndDate = $("#PolicyEndDate").val();
    var isFullYearCheckControl = false;
    var transactionId = $("#TransactionId").val();

    //if return back to modify, will check the fullyear flag
    if ($("#FullYearFlag").attr("checked") && isFirst) {
        isFullYearCheckControl = true;
    }
    else {
        //check product max duration
        if (!CheckProductMaxDuration()) {
            //get plan full year flag
            var fullyearflag;
            $.ajaxAntiForgery({
                url: "GetPlanFullyearFlag",
                data: {
                    plancode: plancode
                },
                dataType: "json",
                type: "POST",
                error: function () {
                    $("#PolicyEndDate").parent().find(".error").html("计划全年标志获取失败");
                },
                success: function (data) {
                    fullyearflag = data["fullyearflag"];
                    //reset control status
                    getPriceControlReset(isFirst, fullyearflag);
                }
            })
            return;
        }
    }

    $.ajaxAntiForgery({
        url: "GetPrices",
        data: {
            plancode: plancode,
            productCode: productCode,
            policyStartDate: policyStartDate,
            policyEndDate: policyEndDate,
            isFullYear: isFullYearCheckControl,
            TransactionId: transactionId
        },
        dataType: "json",
        type: "POST",
        error: function () {
            $("#PolicyEndDate").parent().find(".error").html("询价失败");
        },
        success: function (data) {
            var adultPrice = data["adultprice"];
            var childPrice = data["childprice"];
            var fullyearflag = data["fullyearflag"];
            var invoke_Sucessful = data["invoke_Sucessful"];
            if (invoke_Sucessful == "True") {
                $("#PriceOfChild").val(childPrice);
                $("#PriceOfAdult").val(adultPrice);
                $("#adultPricespan").html(adultPrice);
                $("#childpricespan").html(childPrice);
                $("#PolicyEndDate").parent().find(".error").html("");
            }
            else {
                $("#PolicyEndDate").parent().find(".error").html("询价失败");
            }

            //reset control status
            getPriceControlReset(isFirst, fullyearflag);
        }
    })
}
function BindPlanRadioButtonEvent() {

    $("input[name=PlanCode]").each(function () {
        $(this).bind("change", function () {
            DynamicRadioClick();
        });
    })
}
function DynamicRadioClick() {
    var end = $("#PolicyEndDate").val();
    var start = $("#PolicyStartDate").val();
    if (!CompareDate(start, end)) {
        //$("#PolicyEndDate").parent().find(".error").html("保单结束日期不能早于保单开始日期");
        $("#PolicyEndDate").val(start)
        days = 1;
        //return;
    }
    
    getPrices(true, false, false);

    ShowGermanyEndorsementOption(true);
}
//get price by change plan options
//isRadio: whether radio button cause the quote price
//isFullYear: whether it is invoked by full year control 
//isFullChecked: Whether the full year checkbox checked
function getPrices(isRadio, isFullYearCheckControl, isFullChecked) {
    var plancode;
    if (isRadio) {
        //if (event.propertyName != "checked" && event.propertyName != "") return;
        //if (!event.srcElement.checked)
        //    return;
        //reset policy end date visible and related value once we change plan radio button event
        plancode = event.srcElement.value;
        $("#FullYearFlag").attr("checked", false);
        $("#fullyearhide").show();
        $("#fullyearhidetext").show();

        var end = $("#PolicyEndDate").val();
        var start = $("#PolicyStartDate").val();
        var days = DiffLong(start, end) + 1;

        $("#DaysOfPolicy").html(days);
    }
    else {
        var plancode = $("input[id=PlanCode]:checked").val();
    }

    //Get parameter values from control
    var productCode = $("#ProductCode").val();
    var policyStartDate = $("#PolicyStartDate").val();
    var policyEndDate = $("#PolicyEndDate").val();
    var transactionId = $("#TransactionId").val();
    //if return back to modify, will check the fullyear flag
    if (!$("#FullYearFlag").attr("checked")) {
        //check product max duration
        if (!CheckProductMaxDuration()) {
            return;
        }
    }

    $.ajaxAntiForgery({
        url: "GetPrices",//Student@Url.Action('GetPrices', 'Order')",
        data: {
            plancode: plancode,
            productCode: productCode,
            policyStartDate: policyStartDate,
            policyEndDate: policyEndDate,
            isFullYear: isFullChecked,
            TransactionId: transactionId
        },
        dataType: "json",
        type: "POST",
        error: function () {
            $("#PolicyEndDate").parent().find(".error").html("询价失败");
        },
        success: function (data) {
            var adultPrice = data["adultprice"];
            var childPrice = data["childprice"];
            var fullyearflag = data["fullyearflag"];

            var invoke_Sucessful = data["invoke_Sucessful"];
            if (invoke_Sucessful == "True") {
                $("#PriceOfChild").val(childPrice);
                $("#PriceOfAdult").val(adultPrice);
                $("#adultPricespan").html(adultPrice);
                $("#childpricespan").html(childPrice);
                //$("#PolicyEndDate").parent().find(".error").html("");
            }
            else {
                $("#PolicyEndDate").parent().find(".error").html("询价失败");
            }

            if (!isFullChecked) {
                $("#FullYearFlag").attr("checked", false);
                if (fullyearflag == "True") {
                    $("#FullYearFlag").removeAttr("disabled");
                }
                else {
                    $("#FullYearFlag").attr("disabled", "");
                }
            }
        }
    })
}

function DateIsInRange(birthday, policyStartDate, min, max) {
    //get date type
    var birth = new Date(Date.parse(birthday.replace(/-/g, "/")));
    var birthyear = birth.getFullYear();
    var birthMonth = birth.getMonth();
    var birthDayNum = birth.getDate();

    //policy duration is from policy start date, not today[Bright 20140710]
    var now = new Date(Date.parse(policyStartDate.replace(/-/g, "/")));
    var nowyear = now.getFullYear();
    var nowMonth = now.getMonth();
    var nowDay = now.getDate();
    //alert(birthMonth);
    //check whehter it is less than min
    if (nowyear - birthyear < min) {
        return false;
    }
    //year is same, will check month and days
    else if (nowyear - birthyear == min) {
        //check month
        if (nowMonth - birthMonth > 0) {
            return true;
        }
        else if (nowMonth - birthMonth < 0) {
            return false;
        }
        else if (nowMonth - birthMonth == 0) {
            //check day
            if (birthDayNum - nowDay > 0) {
                return false;
            }
            else {
                return true;
            }
        }
    }
    else {
        //check whehter it is more than max year old
        if (nowyear - birthyear > max) {
            return false; //more than max year old
        }
        else if (nowyear - birthyear == max) {
            //check month
            if (nowMonth - birthMonth < 0) {
                return true;
            }
            else if (nowMonth - birthMonth > 0) {
                return false;
            }
            else if (nowMonth - birthMonth == 0) {
                //check day
                if (birthDayNum - nowDay > 0) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        else {
            return true;
        }
    }
}

function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//get the date after today for interval AddDayCount
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    var d = dd.getDate();

    if (d < 10) {
        d = "0" + d;
    }

    if (m >= 10) {
        return y + "-" + m + "-" + d;
    }
    else {
        return y + "-0" + m + "-" + d;
    }
}

// Added by Justin 2015/03/12 Start
function GetAnnualPolicyEndDate(beginDate) {
    if (!isDate(beginDate)) {
        return "";
    }

    var tempDate = new Date(Date.parse(beginDate.replace(/-/g, "/")));
    var year = tempDate.getFullYear();
    tempDate.setFullYear(year + 1);
    
    var date = tempDate.getDate();
    tempDate.setDate(date - 1); // in JS (2016-02-29) + 1year = (2017-03-01), matched the speicial case start date 2016-02-29, end date 2017-02-28

    var y = tempDate.getFullYear();
    var m = tempDate.getMonth() + 1;
    var d = tempDate.getDate();

    if (d < 10) {
        d = "0" + d;
    }

    if (m >= 10) {
        return y + "-" + m + "-" + d;
    }
    else {
        return y + "-0" + m + "-" + d;
    }
}
// Added by Justin 2015/03/12 End

function CompareDate(datestr1, datestr2) {
    var date1 = new Date(Date.parse(datestr1.replace(/-/g, "/")));
    var date2 = new Date(Date.parse(datestr2.replace(/-/g, "/")));

    var isLater = false;

    if (date1.getTime() <= date2.getTime()) {
        isLater = true;
    }

    return isLater;
}
function DiffLong(datestr1, datestr2) {
    var date1 = new Date(Date.parse(datestr1.replace(/-/g, "/")));
    var date2 = new Date(Date.parse(datestr2.replace(/-/g, "/")));
    var datetimeTemp;
    var isLater = true;

    if (date1.getTime() > date2.getTime()) {
        isLater = false;
        datetimeTemp = date1;
        date1 = date2;
        date2 = datetimeTemp;
    }

    difference = date2.getTime() - date1.getTime();
    thisdays = Math.floor(difference / (1000 * 60 * 60 * 24));

    difference = difference - thisdays * (1000 * 60 * 60 * 24);
    thishours = Math.floor(difference / (1000 * 60 * 60));

    var strRet = thisdays;

    return strRet;
}
function ShowOrdersummary() {
    //[fix bug:policy end date can't be earlier than start date at background][Bright Bian 2014-07-03]
    //policy duration date

    var end = $("#PolicyEndDate").val();
    var start = $("#PolicyStartDate").val();
    var days = DiffLong(start, end) + 1;

    if ($("#FullYearFlag").attr("checked")) {
        var pEndDate = GetAnnualPolicyEndDate(start); // updated by Justin, 2015-03-12
        days = DiffLong(start, pEndDate) + 1;
    }
    $("#DaysOfPolicy").html(days);

    //if (this.id == "PolicyStartDate" || this.id == "PolicyEndDate" || this.id == "ApplicantBrithDate") {
    var birthdays = $("#new_him_html").find("input[name$= BIRTH_DATE]");

    if (birthdays.length == 0) {
        return;
    }

    var countAdult = 0, countChild = 0, countOld = 0;
    //policy duration is from policy start date, not today[Bright 20140710]       
    var policyStartDate = $("#PolicyStartDate").val();
    //calculate insured adult and child amount
    for (var i = 0; i < birthdays.length; i++) {
        //current insured birdhday
        var birthday = birthdays.get(i).value;

        if (birthday == "") {
            continue;
        }
        //check adult and child
        //policy duration is from policy start date, not today[Bright 20140710]
        var policyStartDate = $("#PolicyStartDate").val();
        if (DateIsInRange(birthday, policyStartDate, 1, 18)) {
            countChild = countChild + 1;
        }
            //policy duration is from policy start date, not today[Bright 20140710]        
        else if (DateIsInRange(birthday, policyStartDate, 18, 5000)) {
            countAdult = countAdult + 1;
            //TW product, old man is double price
            if (DateIsInRange(birthday, policyStartDate, 81, 91))
            {
                countOld = countOld + 1;
                countAdult = countAdult - 1;
            }
        }
    }

    var childtotal, adulttotal, oldtotal;

    if (countAdult > 0) {
        $("#adultSummary").show();
        //amout        
        $("#adultSummary").find(".amount").html(countAdult);

        //product
        var productName = $("#ProductCode option:selected").html();
        $("#adultSummary").find(".productAdult").html(productName);

        //plan
        var planName = $('input:radio[id="PlanCode"]:checked').next().text()
        if ($("#FullYearFlag").attr("checked")) {
            planName = "全年" + planName;
        }

        $("#adultSummary").find(".planAdult").html(planName);

        //date summary
        var startdate = $("#PolicyStartDate").val();
        var enddate = $("#PolicyEndDate").val();
        if ($("#FullYearFlag").attr("checked")) {
            enddate = GetAnnualPolicyEndDate(startdate); // updated by Justin, 2015-03-12
        }
        var dateStr = startdate + " 至 " + enddate;
        $("#adultSummary").find(".dateAdult").html(dateStr);

        //price
        var price = $("#PriceOfAdult").val();
        $("#adultSummary").find(".priceAdult").html(price);

        //adult total prices
        //var price = $("#PriceOfAdult").val();
        adulttotal = parseInt(price) * countAdult;
        $("#adultSummary").find(".totalpriceadult").html(adulttotal);
    }
    else {
        $("#adultSummary").hide();
        $("#adultSummary").find(".totalpriceadult").html("0");
        adulttotal = 0;
    }
    //Only tw product has old man price
    if (countOld > 0 && $("#ProductCode option:selected").val()=="021085") {
        $("#oldSummary").show();
        //amout        
        $("#oldSummary").find(".amount").html(countOld);

        //product
        var productName = $("#ProductCode option:selected").html();
        $("#oldSummary").find(".productOld").html(productName);

        //plan
        var planName = $('input:radio[id="PlanCode"]:checked').next().text()
        if ($("#FullYearFlag").attr("checked")) {
            planName = "全年" + planName;
        }

        $("#oldSummary").find(".planOld").html(planName);

        //date summary
        var startdate = $("#PolicyStartDate").val();
        var enddate = $("#PolicyEndDate").val();
        if ($("#FullYearFlag").attr("checked")) {
            enddate = GetAnnualPolicyEndDate(startdate); // updated by Justin, 2015-03-12
        }
        var dateStr = startdate + " 至 " + enddate;
        $("#oldSummary").find(".dateOld").html(dateStr);

        //price
        var price = $("#PriceOfAdult").val();
        $("#oldSummary").find(".priceOld").html(parseInt(price) * 2);

        //old total prices
        oldtotal = parseInt(price) * countOld*2;
        $("#oldSummary").find(".totalpriceold").html(oldtotal);
    }
    else {
        $("#oldSummary").hide();
        $("#oldSummary").find(".totalpriceold").html("0");
        oldtotal = 0;
    }
    if (countChild > 0) {

        $("#childSummary").show();
        //amout        
        $("#childSummary").find(".amount").html(countChild);

        //product
        var productName = $("#ProductCode option:selected").html();
        $("#childSummary").find(".productChild").html(productName);

        //plan
        var planName = $('input:radio[id="PlanCode"]:checked').next().text()
        //debugger;

        if ($("#FullYearFlag").attr("checked")) {
            planName = "全年" + planName;
        }

        $("#childSummary").find(".planChild").html(planName);

        //date summary
        var startdate = $("#PolicyStartDate").val();
        var enddate = $("#PolicyEndDate").val();
        if ($("#FullYearFlag").attr("checked")) {
            enddate = GetAnnualPolicyEndDate(startdate); // Modified by Justin 2015-03-12
        }
        var dateStr = startdate + " 至 " + enddate;
        $("#childSummary").find(".dateChild").html(dateStr);

        //price
        var price = $("#PriceOfChild").val();
        $("#childSummary").find(".priceChild").html(price);

        //adult total prices
        //var price = $("#PriceOfAdult").val();
        childtotal = parseInt(price) * countChild;
        $("#childSummary").find(".totalpriceChild").html(childtotal);
    }
    else {
        $("#childSummary").hide();
        $("#childSummary").find(".totalpriceChild").html("0");
        childtotal = 0;
    }

    var totalFee = childtotal + adulttotal + oldtotal;
    $("#totalFee").html(totalFee);
    $("#PolicyTotalPrice").val(totalFee);

    // when product changes, the Ajax may run after script of Germany endorsement flag checking, add the checking in timer.
    ShowGermanyEndorsementOption(false);
}

// Click the check code img to refresh the image
function funClickCheckCode(obj, address) {

    var now = new Date();
    var year = now.getYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var milSecond = now.getMilliseconds();
    var rn = year + "" + month + "" + day + "" + hour + "" + minute + "" + second + "" + milSecond;

    obj.src = address + "?r=" + rn;
}

// Add by Lynn 2014/07/17 Start
function checkInsuredDuplicate() {
    var insuredCount = $(".insured_info").length;
    var tblInfo = $(".insured_info");
    var insuredArr = new Array();
    var strInsured = "";

    for (var i = 0; i < insuredCount; i++) {
        strInsured = "";

        if ($("#InsuredPersons_" + i + "__NAME").val() == undefined) {
            strInsured += $("#Insured" + i + "__InsuredName").val();
        }
        else {
            strInsured += $("#InsuredPersons_" + i + "__NAME").val();
        }
        if ($("#InsuredPersons_" + i + "__ID_TYPE_ID").val() == undefined) {
            strInsured += $("#Insured" + i + "__ID_Type_ID").val();
        }
        else {
            strInsured += $("#InsuredPersons_" + i + "__ID_TYPE_ID").val();
        }
        if ($("#InsuredPersons_" + i + "__ID_NO").val() == undefined) {
            strInsured += $("#Insured" + i + "__ID_NO").val();
        }
        else {
            strInsured += $("#InsuredPersons_" + i + "__ID_NO").val();
        }
        insuredArr.push(strInsured);
    }

    for (var i = 0; i < insuredCount; i++) {
        for (var j = 0; j < insuredCount; j++) {
            if (i != j && insuredArr[i] == insuredArr[j]) {
                $(".insured_info").eq(j).find("tr").eq(3).find("span").eq(3).html("被保险人信息不能重复，请更正");
                $(".insured_info").eq(i).find("tr").eq(3).find("span").eq(3).html("被保险人信息不能重复，请更正");
                break;
            }
            else {
                $(".insured_info").eq(i).find("tr").eq(3).find("span").eq(3).html('');
                $(".insured_info").eq(j).find("tr").eq(3).find("span").eq(3).html('');
            }
        }
    }

}
// Add by Lynn 2014/07/17 End

// for Germany Endorsement, only shown for "万国游踪 钻石计划"
function ShowGermanyEndorsementOption(isChanged)
{
    var planCode = $('input:radio[id="PlanCode"]:checked').val();
    
    // when come back from order confirm page, the plan code is "undefined" firstly as Ajax
    // if Ajax doesn't complete to get plan code, not to set the germany endorsement status.
    // it would be not correct to put as unchecked by timer, need this condition
    // it also has another an enhanced checking in backgroud code
    if (planCode == undefined) {
        return;
    }

    if ($("#ExpressRequired").is(':checked') && planCode == "ITADMD") {
        $("#germanyEndorsementCheck").show();
    }
    else {
        $("#IS_GM_ENDORSEMENT").attr("checked", false);
        $("#germanyEndorsementCheck").hide()
    }
}